<template>
  <div class="goods-detail-container">
    <!-- 商品展示区 -->
    <div class="goods-display" style="text-align: left">
<!--      <div class="goods-image">-->
<!--        <img :src="goodsDto.coverImage" alt="商品图片">-->
<!--      </div>-->
      <div class="goods-image">
        <div v-if="goodsDto.detailImage">
          <el-carousel height="400px">
            <el-carousel-item v-for="(image, index) in goodsDto.detailImage.split(',')" :key="index">
              <img :src="image" alt="商品图片" class="carousel-image">
            </el-carousel-item>
          </el-carousel>
        </div>
        <img v-else :src="goodsDto.coverImage" alt="商品图片">
      </div>

      <div class="goods-info">
        <h1 class="goods-title">{{ goodsDto.goodsName }}</h1>
        <p class="goods-subtitle">{{ goodsDto.goodsFeature }}</p>

        <div class="goods-brand">{{ brandName }}</div>

        <div class="goods-price">
          <span class="sale-price">{{ goodsDto.salePrice }}元</span>
          <span class="original-price" v-if="goodsDto.originalPrice">{{ goodsDto.originalPrice }}元</span>
        </div>

        <!-- 商品配置选择 -->
        <div class="goods-config" v-if="configurations.length > 0">
          <div class="config-title">选择配置</div>
          <div class="config-options">
            <div
                v-for="config in configurations"
                :key="config.id"
                :class="['config-option', {active: selectedConfigId === config.id}]"
                @click="selectConfig(config.id)"
            >
              {{ config.configuration }}
            </div>
          </div>
        </div>

        <!-- 商品颜色选择 -->
        <div class="goods-color" v-if="colors.length > 0">
          <div class="color-title">选择颜色</div>
          <div class="color-options">
            <div
                v-for="color in colors"
                :key="color.id"
                :class="['color-option', {active: selectedColorId === color.id}]"
                @click="selectColor(color.id)"
            >
              {{ color.color }}
            </div>
          </div>
        </div>

        <!-- 商品版本选择 -->
        <div class="goods-version" v-if="versions.length > 0">
          <div class="version-title">选择版本</div>
          <div class="version-options">
            <div
                v-for="version in versions"
                :key="version.id"
                :class="['version-option', {active: selectedVersionId === version.id}]"
                @click="selectVersion(version.id)"
            >
              {{ version.thali }}
            </div>
          </div>
        </div>

        <!-- 商品总价 -->
        <div class="goods-total">
          <div class="total-label">总计：</div>
          <div class="total-price">{{ totalPrice }}元</div>
        </div>

        <!-- 操作按钮 -->
        <div class="goods-actions">
          <button class="btn-add-cart" @click="addToCart" :disabled="!goodsDto.stock">
            {{ goodsDto.stock ? '加入购物车' : '暂时缺货' }}
          </button>
          <button class="btn-favorite" @click="toggleFavorite">
            <i :class="isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
            收藏
          </button>
        </div>
      </div>
    </div>

    <!-- 商品详情区 -->
    <div class="goods-details">
      <h2 class="details-title">商品详情</h2>
      <div class="details-content" v-html="goodsDto.description"></div>

      <!-- 商品轮播图 -->
      <div class="goods-carousel" v-if="carouselDto.length > 0">
        <h3>商品展示</h3>
        <el-carousel :interval="4000" type="card" height="300px">
          <el-carousel-item v-for="item in carouselDto" :key="item.id">
            <img :src="item.image" :alt="item.carousel_name">
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 商品规格参数 -->
      <div class="goods-specs" v-if="goodsDto.goodsFeature">
        <h3>规格参数</h3>
        <div class="specs-list">
          <div class="spec-item">
            <span class="spec-name">商品名称：</span>
            <span class="spec-value">{{ goodsDto.goodsName }}</span>
          </div>
          <div class="spec-item">
            <span class="spec-name">商品特性：</span>
            <span class="spec-value">{{ goodsDto.goodsFeature }}</span>
          </div>
          <!-- 商品配置选择 -->
          <div class="goods-config" v-if="attributeDtoList.length > 0">
            <div class="config-title">选择配置</div>
            <div class="config-options">
              <div
                  v-for="(attr, index) in getUniqueConfigurations()"
                  :key="'config-'+index"
                  :class="['config-option', {active: selectedConfigId === attr.id}]"
                  @click="selectConfig(attr.id)"
              >
                {{ attr.configuration }}
              </div>
            </div>
          </div>

          <!-- 商品颜色选择 -->
          <div class="goods-color" v-if="attributeDtoList.length > 0">
            <div class="color-title">选择颜色</div>
            <div class="color-options">
              <div
                  v-for="(attr, index) in getUniqueColors()"
                  :key="'color-'+index"
                  :class="['color-option', {active: selectedColorId === attr.id}]"
                  @click="selectColor(attr.id)"
              >
                {{ attr.color }}
              </div>
            </div>
          </div>

          <!-- 商品版本选择 -->
          <div class="goods-version" v-if="attributeDtoList.length > 0">
            <div class="version-title">选择版本</div>
            <div class="version-options">
              <div
                  v-for="(attr, index) in getUniqueVersions()"
                  :key="'version-'+index"
                  :class="['version-option', {active: selectedVersionId === attr.id}]"
                  @click="selectVersion(attr.id)"
              >
                {{ attr.thali }}
              </div>
            </div>
          </div>
          <div class="spec-item" v-if="goodsDto.stock">
            <span class="spec-name">库存：</span>
            <span class="spec-value">{{ goodsDto.stock }}件</span>
          </div>
        </div>
      </div>

      <!-- 相关优惠券 -->
      <div class="goods-coupons" v-if="availableCoupons.length > 0">
        <h3>可用优惠券</h3>
        <div class="coupon-list">
          <div class="coupon-item" v-for="coupon in availableCoupons" :key="coupon.id">
            <div class="coupon-amount">¥{{ coupon.discountAmount }}</div>
            <div class="coupon-info">
              <div class="coupon-name">{{ coupon.activityName }}</div>
              <div class="coupon-desc">{{ coupon.description }}</div>
              <div class="coupon-condition">满{{ coupon.minCondition }}元可用</div>
              <div class="coupon-time">{{ formatDate(coupon.startTime) }} - {{ formatDate(coupon.endTime) }}</div>
            </div>
            <div class="coupon-action">
              <button class="btn-get-coupon" @click="getCoupon(coupon)" :disabled="!coupon.remainingQuota">
                {{ coupon.remainingQuota ? '领取' : '已领完' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {sendRequest} from "@/util/request";

export default {
  name: 'GoodsDetail',
  data() {
    return {
      goodsId: null,
      goodsDto: {}, // 商品基本信息
      carouselDtoList: [], // 轮播图列表
      attributeDtoList: [], // 属性列表
      promotionDtoList: [], // 优惠卷列表

      selectedConfigId: null,
      selectedColorId: null,
      selectedVersionId: null,

      isFavorite: false,
      brandName: '小米自营', // 默认品牌名称

      // 价格相关
      basePrice: 0,
      configPrice: 0,
      colorPrice: 0,
      versionPrice: 0
    };
  },
  computed: {
    // 计算选中的配置对象
    selectedConfig() {
      return this.attributeDtoList.find(item => item.id === this.selectedConfigId) || null;
    },
// 计算选中的颜色对象
    selectedColor() {
      return this.attributeDtoList.find(item => item.id === this.selectedColorId) || null;
    },
// 计算选中的版本对象
    selectedVersion() {
      return this.attributeDtoList.find(item => item.id === this.selectedVersionId) || null;
    },
    // 计算总价
    totalPrice() {
      let total = this.basePrice;

      // 根据选择的配置、颜色和版本计算价格
      if (this.selectedConfig && this.selectedConfig.priceAdjustment) {
        total += this.selectedConfig.priceAdjustment;
      }

      if (this.selectedColor && this.selectedColor.priceAdjustment) {
        total += this.selectedColor.priceAdjustment;
      }

      if (this.selectedVersion && this.selectedVersion.priceAdjustment) {
        total += this.selectedVersion.priceAdjustment;
      }

      return total;
    },
    // 从属性列表中提取配置选项
    configurations() {
      const configMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.configuration && !configMap.has(item.configuration)) {
          configMap.set(item.configuration, {
            id: item.id,
            configuration: item.configuration,
            priceAdjustment: 0
          });
        }
      });
      return Array.from(configMap.values());
    },
    // 从属性列表中提取颜色选项
    colors() {
      const colorMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.color && !colorMap.has(item.color)) {
          colorMap.set(item.color, {
            id: item.id,
            color: item.color,
            priceAdjustment: 0
          });
        }
      });
      return Array.from(colorMap.values());
    },
    // 从属性列表中提取版本选项
    versions() {
      const versionMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.thali && !versionMap.has(item.thali)) {
          versionMap.set(item.thali, {
            id: item.id,
            thali: item.thali,
            priceAdjustment: 0
          });
        }
      });
      return Array.from(versionMap.values());
    },
    // 可用于轮播图展示的数据
    carouselDto() {
      return this.carouselDtoList.map(item => ({
        id: item.id,
        carousel_name: item.carouselName,
        image: item.image || this.goodsDto.coverImage,
        is_online: item.isOnline
      }));
    },
    // 可用优惠券
    availableCoupons() {
      return this.promotionDtoList;
    }
  },
  created() {
    // 从路由参数获取商品ID
    this.goodsId = this.$route.params.id || 1; // 默认为1，方便测试

    // 获取商品详情
    this.fetchGoodsDetail();
  },
  methods: {
    // 获取唯一的配置选项
    getUniqueConfigurations() {
      const configMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.configuration && !configMap.has(item.configuration)) {
          configMap.set(item.configuration, {
            id: item.id,
            configuration: item.configuration
          });
        }
      });
      return Array.from(configMap.values());
    },

// 获取唯一的颜色选项
    getUniqueColors() {
      const colorMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.color && !colorMap.has(item.color)) {
          colorMap.set(item.color, {
            id: item.id,
            color: item.color
          });
        }
      });
      return Array.from(colorMap.values());
    },

// 获取唯一的版本选项
    getUniqueVersions() {
      const versionMap = new Map();
      this.attributeDtoList.forEach(item => {
        if (item.thali && !versionMap.has(item.thali)) {
          versionMap.set(item.thali, {
            id: item.id,
            thali: item.thali
          });
        }
      });
      return Array.from(versionMap.values());
    },
    // 获取商品详情
    fetchGoodsDetail() {
      this.loading = true
      sendRequest('get', '/index/goods/selectCarouselAndPromotionByGoodsId/' + this.goodsId).then(res => {
        if (res.code === 200 && res.selectCarouselAndPromotionByGoodsId.length > 0) {
          const goodsData = res.selectCarouselAndPromotionByGoodsId[0];

          // 设置商品基本信息
          this.goodsDto = {
            id: goodsData.id,
            goodsName: goodsData.goodsName,
            goodsFeature: goodsData.goodsFeature,
            originalPrice: goodsData.originalPrice,
            salePrice: goodsData.salePrice,
            stock: goodsData.stock,
            virtualSales: goodsData.virtualSales,
            coverImage: goodsData.coverImage,
            detailImage: goodsData.detailImage,
            description: goodsData.description || '<p>暂无详细描述</p>'
          };

          // 设置基础价格
          this.basePrice = this.goodsDto.salePrice || this.goodsDto.originalPrice;

          // 设置轮播图列表
          this.carouselDtoList = goodsData.carouselDtoList || [];

          // 设置属性列表
          this.attributeDtoList = goodsData.attributeDtoList || [];

          // 设置优惠券列表
          this.promotionDtoList = goodsData.promotionDtoList || [];

          // 设置默认选中的选项
          this.setDefaultSelections();
        } else {
          this.$message.error('获取商品详情失败');
        }
        this.loading = false
      }).catch(error => {
        console.error('获取商品详情出错:', error);
        this.$message.error('获取商品详情出错');
        this.loading = false
      });
    },

    // 设置默认选中的选项
    setDefaultSelections() {
      // 设置默认选中的配置
      if (this.configurations.length > 0) {
        this.selectedConfigId = this.configurations[0].id;
      }

      // 设置默认选中的颜色
      if (this.colors.length > 0) {
        this.selectedColorId = this.colors[0].id;
      }

      // 设置默认选中的版本
      if (this.versions.length > 0) {
        this.selectedVersionId = this.versions[0].id;
      }
    },

    // 选择配置
    selectConfig(configId) {
      this.selectedConfigId = configId;
    },

    // 选择颜色
    selectColor(colorId) {
      this.selectedColorId = colorId;
    },

    // 选择版本
    selectVersion(versionId) {
      this.selectedVersionId = versionId;
    },

    // 加入购物车
    addToCart() {
      if (!this.goodsDto.stock) {
        this.$message.warning('商品暂时缺货');
        return;
      }

      // 构建购物车商品对象
      const cartItem = {
        goodsId: this.goodsDto.id,
        goodsName: this.goodsDto.goodsName,
        price: this.totalPrice,
        quantity: 1,
        configId: this.selectedConfigId,
        configName: this.selectedConfig ? this.selectedConfig.configuration : '',
        colorId: this.selectedColorId,
        colorName: this.selectedColor ? this.selectedColor.color : '',
        versionId: this.selectedVersionId,
        versionName: this.selectedVersion ? this.selectedVersion.thali : '',
        coverImage: this.goodsDto.coverImage
      };

      // 实际API调用
      this.$http.post('/api/cart/add', cartItem).then((res) => {
        console.log(res)
        this.$message.success('成功加入购物车');
      }).catch(error => {
        console.error('加入购物车失败:', error);
        this.$message.error('加入购物车失败');
      });
    },

    // 切换收藏状态
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;

      // 实际API调用
      this.$http.post(`/api/favorites/toggle`, {
        goodsId: this.goodsDto.id,
        isFavorite: this.isFavorite
      }).then((res) => {
        const message = this.isFavorite ? '已添加到收藏' : '已取消收藏';
        this.$message.success(message+res);
      }).catch(error => {
        console.error('收藏操作失败:', error);
        this.$message.error('收藏操作失败');
      });
    },

    // 领取优惠券
    getCoupon(coupon) {
      if (coupon.remainingQuota <= 0) {
        this.$message.warning('优惠券已领完');
        return;
      }

      // 实际API调用
      this.$http.post('/api/coupons/redeem', {
        couponId: coupon.id,
        redeemCode: coupon.redeemCode
      }).then((res) => {
        this.$message.success('优惠券领取成功'+res);
        // 更新优惠券剩余数量
        coupon.remainingQuota--;
      }).catch(error => {
        console.error('领取优惠券失败:', error);
        this.$message.error('领取优惠券失败');
      });
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.goods-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.goods-display {
  display: flex;
  margin-bottom: 40px;
}

.goods-image {
  flex: 1;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.goods-image img {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.goods-info {
  flex: 1;
  padding: 20px;
}

.goods-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 10px;
  color: #333;
}

.goods-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0 0 15px;
}

.goods-brand {
  font-size: 14px;
  color: #ff6700;
  margin-bottom: 15px;
}

.goods-price {
  margin-bottom: 20px;
}

.sale-price {
  font-size: 24px;
  color: #ff6700;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.config-title, .color-title, .version-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.config-options, .color-options, .version-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.config-option, .color-option, .version-option {
  padding: 10px 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.config-option:hover, .color-option:hover, .version-option:hover {
  border-color: #ff6700;
}

.config-option.active, .color-option.active, .version-option.active {
  border-color: #ff6700;
  color: #ff6700;
}

.goods-total {
  display: flex;
  align-items: center;
  margin: 30px 0;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.total-label {
  font-size: 16px;
  color: #333;
}

.total-price {
  font-size: 24px;
  color: #ff6700;
  font-weight: bold;
  margin-left: 10px;
}

.goods-actions {
  display: flex;
  gap: 15px;
}

.btn-add-cart, .btn-favorite {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.btn-add-cart {
  background-color: #ff6700;
  color: white;
}

.btn-add-cart:hover {
  background-color: #f25807;
}

.btn-add-cart:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.btn-favorite {
  background-color: #f5f5f5;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-favorite i {
  margin-right: 5px;
}

.btn-favorite:hover {
  background-color: #e0e0e0;
}

.goods-details {
  margin-top: 40px;
}

.details-title {
  font-size: 20px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.details-content {
  margin-bottom: 30px;
}

.goods-carousel {
  margin: 30px 0;
}

.goods-carousel h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.goods-specs {
  margin-top: 30px;
}

.goods-specs h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.specs-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.spec-item {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.spec-name {
  color: #666;
}

.spec-value {
  color: #333;
  font-weight: 500;
}

.goods-coupons {
  margin-top: 30px;
}

.goods-coupons h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.coupon-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.coupon-item {
  display: flex;
  width: 100%;
  max-width: 400px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.coupon-amount {
  width: 100px;
  background-color: #ff6700;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
}

.coupon-info {
  flex: 1;
  padding: 10px;
}

.coupon-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.coupon-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.coupon-condition {
  font-size: 12px;
  color: #ff6700;
  margin-bottom: 5px;
}

.coupon-time {
  font-size: 12px;
  color: #999;
}

.coupon-action {
  width: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btn-get-coupon {
  padding: 5px 10px;
  background-color: #ff6700;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-get-coupon:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .goods-display {
    flex-direction: column;
  }

  .specs-list {
    grid-template-columns: 1fr;
  }

  .coupon-item {
    max-width: 100%;
  }
}
</style>
